using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Web.Hosting;
using System.Web.Security;
using Webbness.Mvc.Config;
using Webbness.Mvc.Models;
using Webbness.Mvc.SubSonic;

namespace Webbness.Mvc.Security
{
    public class SimpleRoleProvider<TRole, TJoin, TUser> : RoleProvider
        where TUser : SecurityUser<TUser, TJoin, TRole>, new()
        where TRole : SecurityRole<TRole, TJoin, TUser>, new()
        where TJoin : SecurityUserInRole<TRole, TJoin, TUser>, new()
    {
        private RoleRepository<TRole, TJoin, TUser> roleRepository;
        private UserRepository<TUser, TJoin, TRole> userRepository;
        private string applicationName;

        public override string ApplicationName
        {
            get { return applicationName; }
            set { applicationName = value; }
        }

        public override void Initialize(string name, NameValueCollection config)
        {
            if (config == null)
            {
                throw new ArgumentNullException("config");
            }

            if (String.IsNullOrEmpty(name))
            {
                name = "SimpleRoleProvider";
            }

            base.Initialize(name, config);
            applicationName = GetConfigValue(config["applicationName"], HostingEnvironment.ApplicationVirtualPath);

            roleRepository = new RoleRepository<TRole, TJoin, TUser>();
            userRepository = new UserRepository<TUser, TJoin, TRole>();
        }

        public override bool IsUserInRole(string username, string roleName)
        {
            if (ApplicationSettings.DisableSecurity)
                return true;

            foreach (string c in GetRolesForUser(username))
            {
                if (String.Equals(c, roleName, StringComparison.CurrentCultureIgnoreCase))
                    return true;
            }
            return false;
        }

        public override string[] GetRolesForUser(string username)
        {
            if (ApplicationSettings.DisableSecurity)
                return new []{"admin"};

            var user = userRepository.GetUserByUserName(username);

            if (user == null)
                return new string[0];

            int cnt = user.Roles.Count;
            var strRoles = new string[cnt];
            for (int i = 0; i < cnt; i++)
            {
                strRoles[i] = user.Roles[i].RoleName;
            }
            return strRoles;
        }

        public override void CreateRole(string roleName)
        {
            roleRepository.Add(roleName);
            roleRepository.Save();
        }

        public override bool DeleteRole(string roleName, bool throwOnPopulatedRole)
        {
            var role = roleRepository.GetRoleByName(roleName);
            if (role == null)
                return false;
            int cnt = role.Users.Count;

            if (cnt == 0)
                return true;
            if (cnt > 0 && throwOnPopulatedRole)
                throw new ApplicationException("Role has users.");
            roleRepository.Delete(role);
            roleRepository.Save();
            return true;
        }

        public override bool RoleExists(string roleName)
        {
            var role = roleRepository.GetRoleByName(roleName);
            return role != null;
        }

        public override void AddUsersToRoles(string[] usernames, string[] roleNames)
        {
            foreach (string u in usernames)
            {
                foreach (string r in roleNames)
                {
                    if (!IsUserInRole(u, r))
                        roleRepository.AddUserToRole(u, r);
                }
            }
            roleRepository.Save();
        }

        public override void RemoveUsersFromRoles(string[] usernames, string[] roleNames)
        {
            foreach (string u in usernames)
            {
                foreach (string r in roleNames)
                {
                    if (!IsUserInRole(u, r))
                        roleRepository.RemoveUserFromRole(u, r);
                }
            }
            roleRepository.Save();
        }

        public override string[] GetUsersInRole(string roleName)
        {
            var role = roleRepository.GetRoleByName(roleName);
            if (role == null)
                return new string[0];
            var lst = new List<string>();
            foreach (var u in role.Users)
                lst.Add(u.UserName);
            return lst.ToArray();
        }

        public override string[] GetAllRoles()
        {
            var roles = roleRepository.FindAllRoles();
            //if (q == null)
            //    return new string[0];
            //var roles = q.ToArray();
            int cnt = roles.Count();
            var strRoles = new string[cnt];
            for (int i = 0; i < cnt; i++)
                strRoles[i] = roles[i].RoleName;
            return strRoles;
        }

        public override string[] FindUsersInRole(string roleName, string usernameToMatch)
        {
            var lst = new List<string>();
            foreach (var u in roleRepository.FindUsersInRole(roleName, usernameToMatch))
            {
                lst.Add(u.UserName);
            }
            return lst.ToArray();
        }

        private static string GetConfigValue(string configValue, string defaultValue)
        {
            if (String.IsNullOrEmpty(configValue))
            {
                return defaultValue;
            }

            return configValue;
        }
    }
}